//
//  DDWaitInterviewVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 2016/10/25.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

import UIKit
import ReactiveCocoa
@objc (DDInterviewListVC)
class DDInterviewListVC: LDBaseTableViewVC {

    let cellID = "DDInterViewCell"
    
    
    private var titleCountLab:UILabel?
    private var dateModel:DDInterviewDataModel?
    
    dynamic var interviewCount:Int = 0
    var type:LDInterviewStatesType?
    var searchNextPage = 0
    
    override func viewDidLoad() {
        
//        super.viewDidLoad()
        
        initUI()
        initKVO()
        setRefresh()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        requestNet(nil)
    }
    
    //requset
    func requestNet(page:String?) {
        
        //待面试
        let paramsModel = DDInterviewSendModel()
        
        if DDClientInfoManager.clientType() == DDClientType.Boss {
            
            paramsModel.emplyoer_id = DDLoginUserManager.userID()
        } else {
            
            paramsModel.jobfinder_id = DDLoginUserManager.userID()
        }
        
        
        //state 传空
        if type == .WaitInterView {
            
            paramsModel.state = LDInterviewStatesType.WaitInterView.rawValue
        }
        
        
        let dict = paramsModel.yy_modelToJSONObject() as?Dictionary<String,String> ?? [String:String]()
        
        LDUserInfoNet.sharedInstance.getInterviewInfoList(dict, succ: { [weak self] (dictArr) in
            
            self?.dateModel = DDInterviewDataModel.yy_modelWithDictionary(dictArr)
            self?.interviewCount = self?.dateModel?.list.count ?? 0
//            self?.hasNextPage = Int(self?.dateModel?.hase_nextpage ?? "0")!
            self?.tableView.reloadData()
        }) { (err) in
            
        }
    }
    
    //kvo
    func initKVO() {
        
        //待面试个数
        RACObserve(self, "interviewCount").subscribeNext { [weak self] (obj) in
            
            let num = obj as? Int ?? 0
            var showStr:NSString = ""
        
            if self?.type == .All {
                
                
                if DDClientInfoManager.clientType() == DDClientType.Boss {
                    
                    showStr = "我一共发出 \(num) 面试安排"
                    
                } else {
                    
                    showStr = ""
                    self?.tableView.tableHeaderView = nil
                }
                
                
            } else if self?.type == .WaitInterView {
                
                
                if DDClientInfoManager.clientType() == DDClientType.Boss {
                    
                    showStr = "您近期有 \(num) 个面试安排"
                    
                } else {
                    
                    showStr = "您近期有 \(num) 个面试安排"
                }
                
                self?.setRNav()
                
                
            } else {
                
                //隐藏 lab
                self?.tableView.tableHeaderView = nil
                return
            }
            
            
            
            if self?.titleCountLab != nil {
                
                let atr = NSMutableAttributedString(string: showStr as String)
                let range = showStr.rangeOfString("\(num)")
                
                atr.addAttributes([NSForegroundColorAttributeName:LDFontColor.Green,NSFontAttributeName:LDFont.Font15], range: range)
                
                self?.titleCountLab?.attributedText = atr
            }
        }

        

    }
    
    //全部按钮 图标
    func setRNav() {
        
        let bar = UIBarButtonItem().bk_initWithImage(UIImage(named: "common_nav_notebook"), style: .Done) { [weak self] (obj) in
            
            
            let vc = DDInterviewListVC()
            
            if DDClientInfoManager.clientType() == DDClientType.Boss {
                vc.title = "我发起的面试邀请"
            } else {
                vc.title = "我的面试邀请"
            }
            
            vc.type = .All
            self?.navigationController?.pushViewController(vc, animated: true)
            
        } as? UIBarButtonItem
        
        navigationItem.rightBarButtonItem = bar
        

    }
    
    func initUI(){
        
//        title = "待面试"
        tableView.separatorStyle = .None
        tableView.backgroundColor = LDGolbalColor.BgGoundGray
        rdv_tabBarController.setTabBarHidden(true, animated: true)
        tableView.tableHeaderView = getTopView()
        
    }
   
    
    func getTopView() ->UIView {
        
        let topV = UIView.init(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, 30))
        titleCountLab = UILabel.setBaseLab("你一共发出4个面试安排", fontSize: 13, titleColor: LDFontColor.DeepGray, Alignment: .Left)
        topV.addSubview(titleCountLab!)
        
        
        titleCountLab!.snp_makeConstraints { (make) in
            
            make.bottom.equalTo(0)
            make.left.equalTo(15)
            make.height.equalTo(15)
        }
        
        return topV
        
    }

}

extension DDInterviewListVC {
    
    // MARK: - Table view data source
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let vc = DDInterviewVC()
        vc.detailID = dateModel?.list[indexPath.row].id
        
        vc.type = dateModel?.list[indexPath.row].type == "2" ? .Video:.Present
        vc.isWaitInterView = dateModel?.list[indexPath.row].state == "3" ? true : false
        vc.title = "面试详情"
        navigationController?.pushViewController(vc, animated: true)
        
        
    }
    

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dateModel?.list.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? DDInterViewCell
        
        if cell == nil {
            cell = DDInterViewCell(interviewType: nil,cellType: .TopGamp, margin: 14, style: .Default, reuseIdentifier: cellID)
        }
        
        cell?.model = dateModel?.list[indexPath.row]
        
        return cell!
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return dateModel!.list[indexPath.row].getCellH()
    }
}

extension DDInterviewListVC {
    
    
    
    //
    func setRefresh() {
        
        let header = LDBaseRefreshView.sharedInstance.header { [weak self] in
            
            self?.refreshNew()
            self?.tableView.mj_header.endRefreshing()
        }
        tableView.mj_header = header
        
        
        let footer = LDBaseRefreshView.sharedInstance.footer { [weak self] in
            
            self?.refreshMore()
            self?.tableView.mj_footer.endRefreshing()
        }
        
        footer.automaticallyChangeAlpha = true
        tableView.mj_footer = footer
    }
    
    // MARK: - 发送网络请求
    
    func refreshNew() {
        
        requestNet(nil)
    }
    
    //
    func refreshMore() {
        
        
        
        //待面试
        let paramsModel = DDInterviewSendModel()
        
        if DDClientInfoManager.clientType() == DDClientType.Boss {
            
            paramsModel.emplyoer_id = DDLoginUserManager.userID()
        } else {
            
            paramsModel.jobfinder_id = DDLoginUserManager.userID()
        }
        
        
        //state 传空
        if type == .WaitInterView {
            
            paramsModel.state = LDInterviewStatesType.WaitInterView.rawValue
        }
        
        
        var dict = paramsModel.yy_modelToJSONObject() as?Dictionary<String,String> ?? [String:String]()
        dict["page"] = String(format: "%d",searchNextPage)
        
        
        
        if dateModel?.hase_nextpage == "1" {
            searchNextPage += 1
            
            
            LDUserInfoNet.sharedInstance.getInterviewInfoList(dict, succ: { [weak self] (dictArr) in
                
                let moreModel = DDInterviewDataModel.yy_modelWithDictionary(dictArr)
                guard let moreInterview = moreModel?.list else { return }
                
                self?.dateModel?.list.appendContentsOf(moreInterview)
                self?.dateModel?.hase_nextpage = moreModel?.hase_nextpage
                self?.interviewCount = self?.dateModel?.list.count ?? 0
                self?.tableView.reloadData()
            }) { (err) in
                
            }
        }
        
    }
    
    
}

